import React, { Component } from "react";
import { filteremoji } from "../../../util/public";
import "./index.scss";


class Search extends Component {
    constructor(props){
        super(props);
        this.state = {
            keyword: "",
            showCancel: false
        };
    }
    changeValue = (e) => {
        let {
            autoSearch,
            searchMethod
        } = this.props;
        let value = filteremoji(e.target.value);
        if(autoSearch && typeof searchMethod === "function"){
            this.setState({
                showCancel: true
            })
            searchMethod(value);
        }
        this.setState({
            keyword: value
        })
    }
    cancelSearch = () => {
        let {
            searchMethod
        } = this.props;
        this.setState({
            keyword: "",
            showCancel: false
        }, ()=>{
            typeof searchMethod === "function" && searchMethod("");
        });
        
    }
    goSearch = () => {
        let {
            searchMethod
        } = this.props;
        this.setState({
            showCancel: this.state.keyword? true: false
        })
        typeof searchMethod === "function" && searchMethod(this.state.keyword);
    }
    keyHandle = (e) => {
        if(e.keyCode === 13){
            this.goSearch();
        }
    }
    render(){
        let {
            placeholder,
            className,
            style
        } = this.props;
        let {
            keyword,
            showCancel
        } = this.state;
        return (
            <div className={`my_search ${className? className: ""}`} style={{...style}}>
                <input
                value={keyword}
                className="my_search_input"
                type="text" 
                placeholder={placeholder? placeholder: "搜索标题..."}
                onKeyDown={this.keyHandle}
                onChange={this.changeValue} />
                {
                    showCancel?
                    <i className="cancellogo" onClick={this.cancelSearch}></i>:
                    ""
                }
                <i className="searchlogo" onClick={this.goSearch}></i>
            </div>
        )
    }
}

export default Search;